package com.acme.ioniolab.transportfile.implementation;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

import com.acme.ioniolab.transportfile.Client;

public class IOClient implements Client {
	
	@Override
	public void transportFile(String fileName, String host, int port) throws IOException {
		File in = new File(fileName);
		
		if (!in.exists()) {
			throw new IOException("File doesn't exist");
		}
		
		try (Socket socket = new Socket(host, port);
	             FileInputStream inputStream = new FileInputStream(in);
	             DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
	             BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

	            byte[] buffer = new byte[1024];

	            outputStream.writeLong(in.length());
	            int readBytes;
	            while ((readBytes = inputStream.read(buffer)) != -1) {
	                outputStream.write(buffer, 0, readBytes);
	                outputStream.flush();
	            }
	        }
	}

}
